/*
 * main.c
 *
 *  Created on: Mar 5, 2015
 *      Author: hiepnm
 */
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <string.h>
#include <time.h>
#include <errno.h>
#include "libs/lru.h"

#define ONE_MEGABYTE (1<<20)
#define NUM_REQUEST_PUSH 8888			//30MB request
#define CACHE_SIZE (1<<20)				//10MB

static uint64_t length_key(const void *key) {
	return sizeof(uint64_t);
}
static uint64_t length_value(char* value) {
	return sizeof(char) * strlen(value);
}
uint64_t sizeofElement(element_t *e) {
	return sizeof(element_t) + length_key(e->key) + length_value((char*)(e->value));
}
typedef struct pairtest_t {
	uint64_t *key;
	char *value;
} pairtest_t;

//模拟请求，如果查不到就添加之
void request(lruCache* lru, uint64_t* key, char* value)
{
	printf("---------------- request for key=%lld ----------------\n", *key );
	printf("used=%d\n",lru->used );
	printf("realused=%u\n",countTable(lru));
	if(lruGet(lru, key))
	{
		printf("request successfully\n");
	}
	else
	{
		printf("request fail,try to add it to lru\n");
		if(-1 == lruSet(lru, key, value))
		{
			fprintf(stderr, "add to lru failed: %s\n", lruError(errno));
		}
		else
		{
			printf("add to lru successfully\n");
		}
	}
}

void test_set() {
	uint64_t i;

	//1，内存中的数据
	pairtest_t *pairs = (pairtest_t*)malloc(sizeof(pairtest_t) * NUM_REQUEST_PUSH);
	for (i = 0; i < NUM_REQUEST_PUSH; i++) {
		pairs[i].key = (uint64_t*)malloc(sizeof(uint64_t));
		*(pairs[i].key) = i;
		pairs[i].value = (char*)malloc(11*sizeof(char));
		strcpy(pairs[i].value, "0123456789");
	}/*all = 50MB*/

	//2，创建一个lru
	lruCache *lru = lruCreate(CACHE_SIZE, sizeofElement, length_key);
	fprintf(stderr, "lruCache: %p\n",lru);
	fprintf(stderr, "memory size = %ld MB\n",(lru->maxMem)/ONE_MEGABYTE);
	fprintf(stderr, "maxElement = %ld\n",lru->maxElement);
	fprintf(stderr, "-----------------------------------------------\n");
	clock_t start = clock();

	//3，模拟用户请求
	for (i = 0; i < NUM_REQUEST_PUSH; i++)
		request(lru, pairs[i].key, pairs[i].value);

	clock_t elapsedTime = clock() - start;
	fprintf(stderr, "elapsed time: %ld ns\n", elapsedTime);

	//4，释放lru
	lruFree(lru);

	//5，释放内存数据
	free(pairs);
}

int main(int argc, char **argv) {
	test_set();
	return 0;
}
